
import ResInterface, { ResType } from "./ResInterface";

export default class ResItem {

    protected resHelper: ResInterface;

    // 全局资源使用计数器。
    protected static resCountMap: {} = {};

    //尝试加载次数
    private loadCount: number = 0;

    //使用次数
    protected useCount: number = 0;

    //资源id
    private url: string;

    //资源类型
    private type: ResType;

    //加载是否结束
    protected loadFinish: boolean = false;

    //资源本身
    private res: any;

    //需要通知的函数
    private callbackList: Function[] = []


    constructor(helper: ResInterface, url: string, type?: ResType) {
        this.resHelper = helper;
        this.url = url;
        this.type = type;
    }

    addCallback(func: Function) {
        this.callbackList.push(func)
    }

    clearCallback() {
        this.callbackList.length = 0;
    }

    //是否加载完毕
    isDone() {
        return this.loadFinish;
    }

    getUrl() {
        return this.url;
    }

    getType() {
        return this.type;
    }

    getRes() {
        this.addCount();
        if (!this.res) {
            this.res = this.resHelper.getRes(this.url, this.type)
        }
        return this.res;
    }

    /**
     * 加载完成调用
     * @param flag 
     */
    setLoadingFlag(flag: boolean) {
        this.loadFinish = flag;
        while (this.callbackList.length > 0) {
            let func = this.callbackList.shift();
            func(!flag, this)
        }
    }
    /**
     * 由于引擎加载机制，加载完成就已经使用，
     */
    cacheRes(res: any) {
        this.res = res;
        //加载成功后直接加1，以免被其他模块的记载器清理掉。
        this.addCount()
    }

    //获得加载次数
    getLoadCount() {
        return this.loadCount;
    }
    //更新加载次数
    updateLoadCount() {
        this.loadCount++;
    }
    //获得使用次数
    getUseCount() {
        return this.useCount;
    }

    releaseAll() {
        while (this.useCount > 0) {
            this.release();
        }
    }
    release() {
        if (this.useCount > 0) {
            this.subCount();
            if (this.useCount == 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }


    subCount() {
        this.useCount--;
        let key = this.url + this.type;
        // console.log(' ResItem.resCountMap[key]  ',key, ResItem.resCountMap[key] )
        if (ResItem.resCountMap[key] > 0) {
            ResItem.resCountMap[key]--;

            if (ResItem.resCountMap[key] == 0) {
                // console.log('subCount ResItem.resCountMap[key] ', key, ' key ', ResItem.resCountMap[key])
                this.resHelper.release(this.res)
                delete ResItem.resCountMap[key];
            }
        }
    }

    addCount() {
        this.useCount++;
        let key = this.url + this.type
        if (!ResItem.resCountMap[key]) {
            ResItem.resCountMap[key] = 0
        }
        ResItem.resCountMap[key]++;
    }

}
